﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace SpiderHelper.Tools.Sina
{
    /// <summary>
    /// 新浪RSS源访问入口
    /// </summary>
    public class SinaVisitor
    {


        public List<Model.TempDoc> ReadSina(Model.CollectionChannel channel, DavidDB.ADO.DBManager db)
        {
            List<Model.Filter> filters = Model.Filter.GetList();
            List<Model.TempDoc> docs = new List<Model.TempDoc>();
            System.Net.CookieContainer container = new System.Net.CookieContainer();
            Common.Net.Request request = new Common.Net.Request(container);
            string source = "";

            XElement elements = null;
            try
            {
                System.Threading.Thread.Sleep(1000);
                source = request.ReadUrlContent(channel.ChannelURL, "utf-8");
                elements = XElement.Parse(source);
            }
            catch (Exception)
            {
                //   source.Debug();
            }
            if (!string.IsNullOrEmpty(source) && elements != null)
            {
                var query = from el in elements.Descendants("channel").Elements<XElement>("item") select el;

                SinaURLAnalysis analysis = new SinaURLAnalysis();
                foreach (XElement result in query)
                {
                    Model.TempDoc doc = new Model.TempDoc();
                    doc.ChannelId = channel.Id;
                    doc.Description = result.Element("description").Value;
                    doc.Link = result.Element("link").Value;
                    doc.Pdate = DateTime.Now;
                    doc.SiteId = Convert.ToInt32(channel.SiteId);
                    doc.Title = result.Element("title").Value;
                    doc.Author = "";
                    //    Console.WriteLine("发现新的文章【" + channel.ChannelName + "】：" + doc.Title);
                    if (doc.Title.IndexOf("视频") < 0 && doc.Title.IndexOf("播客") < 0 && !doc.IsInserted(doc.Link, db))
                    {
                        bool enSured = false;
                        doc.Content = analysis.AnalysisURLContent(doc.Link, "utf-8", Convert.ToInt32(channel.Id), out enSured);
                        doc.Sured = enSured == true ? 1 : 0;
                        if (!string.IsNullOrEmpty(doc.Content))
                        {
                            //     Console.WriteLine("保存文章【" + channel.ChannelName + "】：" + doc.Title);
                            //    ("保存文章【" + channel.ChannelName + "】：" + doc.Title).Debug();
                            SetTag(doc, filters);

                            docs.Add(doc);
                        }
                        else
                        {
                            //    Console.WriteLine("文章【" + channel.ChannelName + "】：" + doc.Title + "  不能被解析【 " + doc.Link + "】");
                            //   ("文章【" + channel.ChannelName + "】：" + doc.Title + "  不能被解析【 " + doc.Link + "】").Debug();
                        }
                    }
                    else
                    {
                        //   Console.WriteLine("文章【" + channel.ChannelName + "】：" + doc.Title + "  为视频或播客【 " + doc.Link + "】");
                        //  ("文章【" + channel.ChannelName + "】：" + doc.Title + "  为视频或播客【 " + doc.Link + "】").Debug();
                    }
                }
            }
            else
            {
                (channel.ChannelName + "  " + channel.ChannelURL + "  解析失败").Debug();
            }
            return docs;
        }

        private void SetTag(Model.TempDoc doc, List<Model.Filter> filters)
        {
            string tag = "";
            foreach (Model.Filter filter in filters)
            {
                if (doc.Content.IndexOf(filter.KeyValue) >= 0 || doc.Title.IndexOf(filter.KeyValue) >= 0)
                {
                    tag += filter.KeyValue + ",";
                }

            }
            doc.Tag = tag;
        }


        public void InitSinaChannels()
        {
            // List<Model.CollectionChannel> channels = new List<Model.CollectionChannel>();
            Model.CollectionSite _sinaSite = new Model.CollectionSite().GetModel(1);
            System.Net.CookieContainer cont = new System.Net.CookieContainer();
            string content = new Common.Net.Request(cont).ReadUrlContent("http://rss.sina.com.cn/sina_all_opml.xml", _sinaSite.Encode);
            //   content.Debug();

            XElement elements = null;
            try
            {
                elements = XElement.Parse(content);
            }
            catch (Exception)
            {
                //content.Debug();
            }
            var query = from el in elements.Descendants("body").Elements<XElement>("outline") select el;

            SinaURLAnalysis analysis = new SinaURLAnalysis();
            foreach (XElement result in query)
            {
                var _query = from t in result.Elements("outline") select t;
                foreach (XElement t in _query)
                {
                    Model.CollectionChannel c = new Model.CollectionChannel();
                    c.ChannelName = t.Attribute("title").Value;
                    c.ChannelURL = t.Attribute("xmlUrl").Value;
                    //c.Encode = "utf-8";
                    c.SiteId = 1;
                    c.Type = t.Attribute("type").Value;
                    c.Subscribe = 1;
                    DavidDB.ADO.DBManager db = new DavidDB.ADO.DBManager();
                    db.Insert(c);
                    db.Commit();
                    db.Dispose();
                    // Common.ADO.DBManager.Insert(c);
                    //   channels.Add(c);
                }
            }
            // return channels;
        }
    }
}
